package com.ssyc.gsk_master.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.TimePickerView;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.netease.nim.uikit.common.util.sys.TimeUtil;
import com.ssyc.common.base.BaseApplication;
import com.ssyc.common.base.LazyBaseFragment;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.manager.OneKeyShareCallback;
import com.ssyc.common.manager.PickerManager;
import com.ssyc.common.manager.ShareManager;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.KeyBoardUtils;
import com.ssyc.common.utils.SPUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.gsk_master.R;
import com.ssyc.gsk_master.bean.RedPackageResponse;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import cn.sharesdk.framework.Platform;
import okhttp3.Call;

import static java.lang.Float.parseFloat;

public class MasterRedPackageFragment extends LazyBaseFragment implements
        View.OnClickListener {

    // 红包金额
    private EditText etMoney;

    // 红包个数
    private EditText etHbgs;

    // 时效限制
    private TextView tvSxxz;

    // 红包主题
    private EditText etHbzt;

    // 塞进红包的按钮
    private Button btCommit;
    // 总金额
    private String money;
    // 红包个数
    private String redCount;
    // 时效限制
    private String time;
    // 红包主题
    private String hbzt = "学有所成,前程似锦!";
    // 上传的文件地址
    private String filePath;

    // 时间选择控件
    TimePickerView pvTime;

//	private HttpUtils httpUtils1;

    private String url;

//	private RequestParams params;
//
//	private RequestParams params1;

    private String pngName;

    private String themeId = "1";

    private String imagePath;

    private Intent intent;

    protected static final int THEME_ID = 0;

    private String redid;

    private LinearLayout ll_loading;


    @Override
    protected int getLayoutId() {
        return R.layout.master_activity_send_red_package;
    }

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    public void lazyInit(View view, Bundle savedInstanceState) {

        initIntent();

        showContent();
        // 初始化控件
        initView(view);

    }

    /**
     * 接收传值
     */
    private void initIntent() {
        intent = getActivity().getIntent();
        imagePath = intent.getStringExtra("imagePath");
        themeId = intent.getStringExtra("themeId");
        Log.e("test", "imagePath" + imagePath);
        Log.e("test", "themeId" + themeId);
    }

    /**
     * 初始化控件
     */
    private void initView(View view) {
        tvSxxz = (TextView) view.findViewById(R.id.tv_sxxz);
        etMoney = (EditText) view.findViewById(R.id.et_money);
        etHbgs = (EditText) view.findViewById(R.id.et_hbgs);
        etHbzt = (EditText) view.findViewById(R.id.et_hbzt);
        btCommit = (Button) view.findViewById(R.id.bt_sjhb);
        ll_loading = (LinearLayout) view.findViewById(R.id.ll_loading);


        tvSxxz.setOnClickListener(this);
        btCommit.setOnClickListener(this);
    }


    @Override
    public void onResume() {
        imagePath = SPUtil.getString(getActivity(), "imagePath");
        themeId = SPUtil.getString(getActivity(), "themeId");

        Log.e("test", "imagePath" + imagePath);
        Log.e("test", "themeId" + themeId);

        super.onResume();
    }

    public String getTime(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    /**
     * 点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {

        if (view.getId() == R.id.tv_sxxz) {

            KeyBoardUtils.closeKeyboard(view);

            // 时效限制
            PickerManager.showPickerByYeaerAndMonthAndDay(getActivity(), new PickerManager.onSelectedListener() {
                @Override
                public void onTimeSelect(Date date, View v) {

                    if (TimeUtil.isTodayAfter(getTime(date))) {
                        tvSxxz.setText("红包有效截止时间");
                        Toast.makeText(getActivity(), "不可选今日之前的日期，请重新选择",
                                Toast.LENGTH_SHORT).show();
                    } else {
                        tvSxxz.setText(getTime(date));
                    }
                }
            });
        } else if (view.getId() == R.id.bt_sjhb) {
            // 塞进红包
            judgeAll();
        }
    }

    /**
     * 点击塞进红包后按钮后的判断完整性方法
     */
    private void judgeAll() {

        // 获取金额
        money = etMoney.getText().toString().trim();
        if (TextUtils.isEmpty(money)) {
            Toast.makeText(getActivity(), "请输入金额", Toast.LENGTH_SHORT).show();
            return;
        }

        // 红包个数
        redCount = etHbgs.getText().toString().trim();
        if (TextUtils.isEmpty(redCount) || Integer.parseInt(redCount) <= 0) {
            Toast.makeText(getActivity(), "您输入的红包金额必须保证每人最少可以领取1元", Toast.LENGTH_SHORT)
                    .show();
            return;
        }

        // 时效限制时间
        time = tvSxxz.getText().toString().trim();
        Log.e("time", time);
        if (TextUtils.isEmpty(time)) {
            Toast.makeText(getActivity(), "请选择红包的截止时间", Toast.LENGTH_SHORT)
                    .show();
            return;
        }
        if ("红包有效期截止时间".equals(time)) {
            Toast.makeText(getActivity(), "请选择红包的截止时间", Toast.LENGTH_SHORT)
                    .show();
            return;
        }

        // 红包主题
        hbzt = etHbzt.getText().toString().trim();

        // 判断总金额/红包个数的值是否大于1,保证每个人至少能拿到1块钱以上的红包
        float getMoney = Float.parseFloat(money) / parseFloat(redCount);
        if (getMoney < 1) {

            // 请保证每个人至少能得到一块钱红包
            moneydialog();

            return;
        }
        dialog();
    }

    private void dialog() {
        final NormalDialog dialog = new NormalDialog(getActivity());
        dialog.content("此红包为拼手气红包，是否确认发送此红包").btnText("取消", "确认发送")//
                .style(NormalDialog.STYLE_TWO)//
                .titleTextSize(23)//
                .show();
        dialog.setCanceledOnTouchOutside(false);

        dialog.setOnBtnClickL(new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                dialog.dismiss();
            }
        }, new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                dialog.dismiss();
                ll_loading.setVisibility(ll_loading.VISIBLE);
                if (hbzt == null || "".equals(hbzt)) {
                    hbzt = "学有所成,前程似锦!";
                }
                if (themeId == null || "".equals(themeId)) {
                    themeId = "1";
                }

                // 请求服务器上传用户填写的相关信息
                if (imagePath == null || "".equals(imagePath)) {
                    creatRedPackage();// 无编辑自定义模板图片
                } else {
                    File f = new File(getActivity().getCacheDir(), imagePath);

                    creatImageRedPackage();
                }
            }
        });
//        dialog.setOnBtnLeftClickL(new OnBtnLeftClickL() {
//
//            @Override
//            public void onBtnLeftClick() {
//                dialog.dismiss();
//            }
//        });
//
//        dialog.setOnBtnRightClickL(new OnBtnRightClickL() {
//
//            @Override
//            public void onBtnRightClick() {
//                dialog.dismiss();
//                ll_loading.setVisibility(ll_loading.VISIBLE);
//                if (hbzt == null || "".equals(hbzt)) {
//                    hbzt = "学有所成,前程似锦!";
//                }
//                if (themeId == null || "".equals(themeId)) {
//                    themeId = "1";
//                }
//
//                // 请求服务器上传用户填写的相关信息
//                if (imagePath == null || "".equals(imagePath)) {
//                    creatRedPackage();// 无编辑自定义模板图片
//                } else {
//                    File f = new File(getActivity().getCacheDir(), imagePath);
//
//                    creatImageRedPackage();
//                }
//            }
//        });
    }

    public String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
        } else {
            sdDir = getActivity().getFilesDir();
        }
        return sdDir.toString();
    }


    /**
     * 创建有主题红包
     */
    private void creatImageRedPackage() {

        Map<String, String> map = new HashMap<>();
        map.put("type", "10");
        map.put("c", AccountUtils.getAccount(getActivity()));
        map.put("role", AccountUtils.getRole(getActivity()));
        map.put("money", money);
        map.put("persons", redCount);
        map.put("expiration", time);
        map.put("title", hbzt);
//        map.put("schoolId", "20001");
//        map.put("schoolName", "曲阳高中");
        map.put("schoolId", AccountUtils.getSchoolId(getActivity()));
        map.put("schoolName", AccountUtils.getSchoolName(getActivity()));
        map.put("skinId", themeId);
        map.put("rtype", "1");
        map.put("platform", "8");

        //添加图片
        String path = imagePath;

//        String path = getSDPath() + "/goldupload/" + imagePath + ".png";
        File f = new File(path);
        Map<String, File> fileMap = new HashMap<>();
        fileMap.put(System.currentTimeMillis() + ".jpg", f);
        Log.i("test", "getSDPath：" + getSDPath());
        Log.i("test", "imagePath：" + imagePath);

        OkHttpUtils.post().url(HttpAdress.REDPACKAGE).params(map).files("picture", fileMap).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                UiUtils.Toast(BaseApplication.ERROR, false);
                ll_loading.setVisibility(ll_loading.GONE);
                Log.i("test", e.toString());
            }

            @Override
            public void onResponse(String response, int id) {
                RedPackageResponse info = null;
                try {
                    info = GsonUtil.jsonToBean(response, RedPackageResponse.class);
                } catch (Exception e) {
                    Log.i("test", "数据解析异常");
                }

                Log.i("test", "有皮肤普通红包" + response);

                if (null != info) {
                    if ("1".equals(info.getState())) {
                        //返回成功

                        redid = info.redId;
                        //分享红包
                        ShareRedpackage();

                    } else {
                        //返回错误
                        UiUtils.Toast("服务器返回异常,状态码是:" + info.getState(), false);
                        Log.i("test", "服务器返回异常,状态码是:" + info.getState());
                    }
                    ll_loading.setVisibility(ll_loading.GONE);
                } else {
                    Log.i("test", "服务器返回数据为空");
                }
            }
        });
    }

    /**
     * 分享红包
     */
    private void ShareRedpackage() {
        if (redid == null || "".equals(redid)) {
            Toast.makeText(getActivity(), "服务器开小差了,请重试", Toast.LENGTH_SHORT).show();
            return;
        }
        if (hbzt == null || "".equals(hbzt)) {
            hbzt = "学有所成,前程似锦!";
        }

        //分享地址
        String shareUrl = HttpAdress.UPDATE_URL + "JPXB/sharePage/pages/JPXGN_JPXB/redBag/redBag.html?rid=" + redid + "&type=1";


        //图标
        String imgUrl = "http://139.129.57.83:8080/Appandroid/jpxblogo.png";

        //分享标题
        String title = "来自" + AccountUtils.getSchoolName(getActivity()) + "学校的红包";

        ShareManager.newInstance().showOneShare(getActivity(), hbzt, shareUrl,
                title, imgUrl, shareUrl, new OneKeyShareCallback() {
                    @Override
                    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                        Log.i("test", "分享成功");
                    }

                    @Override
                    public void onError(Platform platform, int i, Throwable throwable) {
                        Log.i("test", "分享失败");
                    }

                    @Override
                    public void onCancel(Platform platform, int i) {
                        Log.i("test", "取消分享");
                    }
                });
    }


    /**
     * 创建无主题红包
     */
    private void creatRedPackage() {

        Map<String, String> map = new HashMap<>();
        map.put("type", "1");
        map.put("c", AccountUtils.getAccount(getActivity()));
        map.put("role", AccountUtils.getRole(getActivity()));
        map.put("money", money);
        map.put("persons", redCount);
        map.put("expiration", time);
        map.put("title", hbzt);
//        map.put("schoolId", "20001");
//        map.put("schoolName", "曲阳高中");
        map.put("schoolId", AccountUtils.getSchoolId(getActivity()));
        map.put("schoolName", AccountUtils.getSchoolName(getActivity()));
        map.put("skinId", themeId);
        map.put("rtype", "1");
        map.put("platform", "8");

        Log.i("test", "schoolId:" + AccountUtils.getAccount(getActivity()) + "schoolName:" +
                AccountUtils.getAccount(getActivity()) + "expiration:" + time + "skinId:" + themeId);

        HttpUtils.post(HttpAdress.REDPACKAGE, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                UiUtils.Toast(BaseApplication.ERROR, false);
                ll_loading.setVisibility(ll_loading.GONE);
            }

            @Override
            public void onResponse(String response, int id) {

                RedPackageResponse info = null;

                try {
                    info = GsonUtil.jsonToBean(response, RedPackageResponse.class);
                } catch (Exception e) {
                    Log.i("test", "数据解析异常");
                }

                Log.i("test", "普通红包" + response);

                if (null != info) {
                    if ("1".equals(info.getState())) {
                        //返回成功
                        redid = info.redId;
                        //分享红包
                        ShareRedpackage();
                    } else {
                        //返回错误
                        UiUtils.Toast("服务器返回异常,状态码是:" + info.getState(), false);
                        Log.i("test", "服务器返回异常,状态码是:" + info.getState());
                    }
                    ll_loading.setVisibility(ll_loading.GONE);
                } else {
                    Log.i("test", "服务器返回数据为空");
                }
            }
        });
    }


    // 请保证每个人至少能得到一块钱红包
    private void moneydialog() {
        final NormalDialog dialog = new NormalDialog(getActivity());
        dialog.content("您输入的红包金额必须保证每人最少可领取1元").btnText("取消", "确认")//
                .style(NormalDialog.STYLE_TWO)//
                .titleTextSize(23)//
                .show();
        dialog.setCanceledOnTouchOutside(false);

        dialog.setOnBtnClickL(new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                dialog.dismiss();
            }
        }, new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                dialog.dismiss();
            }
        });
//        dialog.setOnBtnLeftClickL(new OnBtnLeftClickL() {
//
//            @Override
//            public void onBtnLeftClick() {
//                dialog.dismiss();
//            }
//        });
//        dialog.setOnBtnRightClickL(new OnBtnRightClickL() {
//
//            @Override
//            public void onBtnRightClick() {
//                dialog.dismiss();
//            }
//        });
    }
}
